﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Specialized;
using Microsoft.SharePoint;
using System.Collections.Generic;
using Exaction.ListSearch.UI.Entities;
using System.Text;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;
using System.Web;

namespace Exaction.ListSearch.WebParts.ListSearch
{
    /// <summary>
    /// User control that deals with the registration process
    /// </summary>
    public partial class ListSearchUserControl : UserControl
    {
        public string SelectedWebPartId;
        public string ParentWebPartId;
        /// <summary>
        /// Gets the share point list field items.
        /// </summary>
        /// <param name="filterCriteria">The filter criteria.</param>
        private List<OptionEntity> GetSharePointListFieldItems()
        {
            List<OptionEntity> fieldItems = new List<OptionEntity>();
            fieldItems = new List<OptionEntity>();
            OptionEntity item;
            SPField field;
            StringCollection viewFieldCollection;
            if (!string.IsNullOrEmpty(SelectedWebPartId) && !SelectedWebPartId.Equals("0"))
            {
                using (SPLimitedWebPartManager wpm = SPContext.Current.Web.GetLimitedWebPartManager(SPUtility.GetPageUrlPath(HttpContext.Current), System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
                {
                    foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wpm.WebParts)
                    {
                        if (wp.ID.Equals(SelectedWebPartId))
                        {
                            XsltListViewWebPart xsltWp = (XsltListViewWebPart)wp;
                            SPList list = SPContext.Current.Web.Lists[xsltWp.ListId];
                            SPView currentView = list.GetView(new Guid(xsltWp.ViewGuid));
                            viewFieldCollection = currentView.ViewFields.ToStringCollection();
                            foreach (string viewField in viewFieldCollection)
                            {
                                field = list.Fields.GetFieldByInternalName(viewField);
                                item = new OptionEntity();
                                item.Id = field.InternalName;
                                item.Title = field.Title;
                                fieldItems.Add(item);
                            }
                        }
                    }
                }
            }
            else if (SPContext.Current.ViewContext.View != null)
            {
                viewFieldCollection = SPContext.Current.ViewContext.View.ViewFields.ToStringCollection();
                foreach (string viewField in viewFieldCollection)
                {
                    field = SPContext.Current.List.Fields.GetFieldByInternalName(viewField);
                    item = new OptionEntity();
                    item.Id = field.InternalName;
                    item.Title = field.Title;
                    fieldItems.Add(item);
                }
            }
            else
            {
                return null;
            }
            return fieldItems;
        }
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            List<OptionEntity> items = GetSharePointListFieldItems();
            if (items != null)
            {
                DdlListFields.DataSource = items;
                DdlListFields.DataTextField = "Title";
                DdlListFields.DataValueField = "Id";
                DdlListFields.DataBind();
            }
            else
            {
                MainContentPnl.Visible = false;
                MessageLbl.Visible = true;
                if (this.Page != null)
                {
                    MessageLbl.Text = "Web part is not configured. Please <a href=\"javascript:ShowToolPane2Wrapper('Edit', '129','" + this.ParentWebPartId + "')\">click here to open the tool pane</a> and select an XsltListViewWebPart from the dropdown.";
                }
            }
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void  OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!IsPostBack)
            {
                if (Request.QueryString["FilterName"] != null)
                {
                    DdlListFields.SelectedValue = Request.QueryString["FilterName"].ToString();
                }

                if (Request.QueryString["FilterMultiValue"] != null)
                {
                    TbSearchText.Text = Request.QueryString["FilterMultiValue"].ToString().Replace("*", "");
                    BtnClearFilter.Visible = true;
                }
            }
        }
        /// <summary>
        /// Handles the Click event of the BtnSearch control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void BtnSearch_Click(object sender, EventArgs e)
        {
            string redirectUrlFormat = "{0}?FilterName={1}&FilterMultiValue={2}";
            string[] selectionCollection = TbSearchText.Text.ToString().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            StringBuilder sbValues = new StringBuilder();
            foreach (string selection in selectionCollection)
            {
                sbValues.Append("*" + selection.Trim() + "*;");
            }

            string urlToRedirectTo = string.Format(redirectUrlFormat, Request.Url.GetLeftPart(UriPartial.Path), DdlListFields.SelectedValue, sbValues.ToString());
            Response.Redirect(urlToRedirectTo);
        }
        /// <summary>
        /// Handles the Click event of the BtnClearFilter control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void BtnClearFilter_Click(object sender, EventArgs e)
        {
            Response.Redirect(Request.Url.GetLeftPart(UriPartial.Path));
        }
    }
}
